const cloud = require('wx-server-sdk');

cloud.init(
    {
      evn: 'my-app-2ezif',
      traceUser: true,
    }
)
const db = cloud.database();
// const _ = db.command();
const createTime = (new Date()).getTime();
exports.main = async () => {
  const wxContext = await cloud.getWXContext();
  var userInfo = '';  //用户信息
  console.log(wxContext.OPENID,'openId');
  //判断用户是否存在
  await db.collection('Users').where({
    openid:wxContext.OPENID
  }).get().then( (res)=>{
    if(res.data.length==0){  //用户不存在
      db.collection('Users').add({
        data:{
          openid: wxContext.OPENID,  //用户的openId
          createTime:createTime,
        }
      }).then((res)=>{
        console.log(res,'添加成功的记录');
      }).catch((err)=>{
        console.log(err,'添加错误');
      })
    }else{
      userInfo = res.data;
    }
    console.log(res);
  }).catch( err=>{
    console.log(err,'用户不存在');
  })
  return {
    openid: wxContext.OPENID,
    appid: wxContext.APPID,
    unionid: wxContext.UNIONID,
    userInfo:userInfo,
  }
}
